/*
package com.chi.elasticSearch;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.MultiSearchRequestBuilder;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeFilterBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.metrics.max.InternalMax;
import org.elasticsearch.search.aggregations.metrics.min.InternalMin;
import org.elasticsearch.search.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import com.botech.skynet.bas.domain.PassBean;
import com.botech.skynet.bas.util.JsonUtil;






*/
/**
 *  本类集成里ES的常用操作
 *  创建索引、删除文档、查询文档、插入文档
 *  
 *  @author     刘萌彦
 *  @version    2014-11-24
 *//*


public class EsDataClient {
	*/
/**获取client的工具类*//*

    private ConEsUitl conESUtil=ConEsUitl.getConEsUtil();
    
    */
/**ES配置文件*//*

	private static final String ESINIT_NAME = "application";
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(ESINIT_NAME);
	*/
/**索引名称、类型名称不再使用调用相应方法所传的参数，而是用下面的成员变量*//*

    private String indexNameCons=RESOURCE_BUNDLE.getString("metaDataIndexName");
    private String typeNameCons=RESOURCE_BUNDLE.getString("metaDataTypeName");
	
    
    */
/**
	 * 建立空索引,索引名字必须为小写
	 * 索引可以这样显示的建立，也可以在插入数据时隐式地建立。
	 * @param indexName 索引名称
	 * @return  CreateIndexResponse 创建索引结果
	 * @exception/throws ElasticsearchException 创建索引异常
	 *//*

	public CreateIndexResponse createIndex (String indexName)throws ElasticsearchException{
		//获取client
		Client client =conESUtil.getClient();
		CreateIndexResponse response=null;
		
		//将索引名称转换为小写
		if(indexName!=null&&!indexName.equals("")){
			indexName=indexName.toLowerCase();
		}
		
		//创建索引
		try {
			response = client.admin().indices()
			 .prepareCreate(indexNameCons)
			 .execute()
			 .actionGet();
		} catch (ElasticsearchException e) {
			throw e;
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
	    return response;
	}
	
	*/
/**
	 * 执行ES简单的查询QueryBuilder
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESsimple (String index,String type,QueryBuilder queryBuilder,int size){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			response = client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			.setFrom(0).setSize(size)
			.execute()
			.actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	*/
/**
	 * 执行ES简单的查询QueryBuilder 增加了排序
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESsimple (String index,String type,QueryBuilder queryBuilder,int size,String sort,String sortOrder){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			SortOrder s = SortOrder.DESC;
			
			if(StringUtils.isNotBlank(sortOrder)&&sortOrder.equals("asc")){
				s = SortOrder.ASC;
			}
			
			//构造查询执行器
			SearchRequestBuilder searchRequestBuilder =  client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			.setFrom(0).setSize(size)
			.addSort(SortBuilders.scoreSort().order(SortOrder.DESC));
			
			if(sort.equals("snapTime")){
				searchRequestBuilder.addSort(sort,s);
			}else{
				searchRequestBuilder.addSort(sort,s).addSort("snapTime",SortOrder.DESC);
			}
			response = searchRequestBuilder.execute().actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	*/
/**
	 * 执行ES分页查询QueryBuilder
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @param startNum    起始条数(从0开始)
	 * @param endNum      查询条数
	 * @param sortField   排序字段
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESPageSort (String index,String type,QueryBuilder queryBuilder,FilterBuilder queryFilter,int startNum,int size,String sortField,String order,float boost){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			SortOrder s = SortOrder.DESC;
			if(StringUtils.isNotBlank(order)&&order.equals("asc")){
				s = SortOrder.ASC;
			}
			
			//构造查询执行器
			SearchRequestBuilder searchRequestBuilder =  client.prepareSearch(indexNameCons)
					.setTypes(typeNameCons)
					.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
					.setQuery(queryBuilder)
					.setPostFilter(queryFilter)
					.addSort(SortBuilders.scoreSort().order(SortOrder.DESC))
					.setFrom(startNum).setSize(size);
			//用户使用其他条件排序时默认增加【时间倒序】
			if(sortField.equals("snapTime")){
				searchRequestBuilder.addSort(sortField,s);
			}else{
				searchRequestBuilder.addSort(sortField,s).addSort("snapTime",SortOrder.DESC);
			}
			//根据号牌的权重 判断是否添加最小得分条件
			if(boost>0f){
				response = searchRequestBuilder.setMinScore(boost).execute()
				.actionGet();
			}else{
				response = searchRequestBuilder.execute().actionGet();
			}
			
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	*/
/**
	 * 执行ES分页查询QueryBuilder
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @param startNum    起始条数(从0开始)
	 * @param endNum      查询条数
	 * @param sortField   排序字段
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESPage (String index,String type,QueryBuilder queryBuilder,FilterBuilder queryFilter, int startNum,int size,float boost){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			if(boost>0f){				
				response = client.prepareSearch(indexNameCons)
				.setTypes(typeNameCons)
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(queryBuilder)
				.setPostFilter(queryFilter)
				.setMinScore(boost)
				.setFrom(startNum).setSize(size)
				.execute()
				.actionGet();
			}else{
				response = client.prepareSearch(indexNameCons)
				.setTypes(typeNameCons)
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(queryBuilder)
				.setPostFilter(queryFilter)
				.setFrom(startNum).setSize(size)
				.execute()
				.actionGet();
			}
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		return response;
	}
	
	
	*/
/**
	 * 执行ES分页查询QueryBuilder（不分页）
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @param sortField   排序字段
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESPageSort (String index,String type,QueryBuilder queryBuilder,BoolFilterBuilder queryFilter,String sortField,String order){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			SortOrder s = SortOrder.DESC;
			if(StringUtils.isNotBlank(order)&&order.equals("asc")){
				s = SortOrder.ASC;
			}
			response = client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			.setPostFilter(queryFilter)
			.addSort(sortField,s)
			.execute()
			.actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	
	*/
/**
	 * 执行ES分页查询QueryBuilder（分页）
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @param sortField   排序字段
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse queryESPageSort (String index,String type,QueryBuilder queryBuilder,String sortField,String order,int startNum,int size){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			SortOrder s = SortOrder.DESC;
			if(StringUtils.isNotBlank(order)&&order.equals("asc")){
				s = SortOrder.ASC;
			}
			
			response = client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			.addSort(sortField,s)
			.setFrom(startNum).setSize(size)
			.execute()
			.actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	*/
/**
	 * 通过UUID删除ES数据
	 * @param index 索引
	 * @param type  类型
	 * 
	 * @return  DeleteResponse 删除结果
	 *//*

	public DeleteResponse delESByUUID(String index,String type,String UUID){
		//获取client
		Client client =conESUtil.getClient();
	    //执行删除
		DeleteResponse response=null;
		try {
			response = client.prepareDelete(indexNameCons,typeNameCons,UUID) 
			.execute() 
			.actionGet();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
	
		return response;
	}
	
	*/
/**
	 * 根据查询删除数据
	 * @param index 索引
	 * @param queryBuilder 查询语句
	 *@return  DeleteByQueryResponse
	 *//*

	public DeleteByQueryResponse delDataByQuery(String index,QueryBuilder queryBuilder){
		//获取client
		Client client =conESUtil.getClient();
		//执行查询语句并删除
		DeleteByQueryResponse response=null;
		try {
			response = client.prepareDeleteByQuery(indexNameCons).setQuery(queryBuilder).execute().actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	*/
/**
	 * 将对象的List集合插入ES
	 * @param  indexName    索引名称
	 * @param  typeName     类型
	 * @param  entityList   需要插入的对象集合
	 * @return  IndexResponse
	 *//*

	public <E> IndexResponse insertESdata(String indexName,String typeName,ArrayList<E> entityList){
		//获取client
		Client client =conESUtil.getClient();
		IndexResponse indexResponse=null;
		
		try {
			if(entityList!=null&&entityList.size()>0){
				//遍历集合，将java对象转为json字符串后插入ES
				for(E temp:entityList){
					//java对象转为Json字符串
					String docc=JsonUtil.writeValueAsString(temp);
					indexResponse= client.prepareIndex(indexNameCons,typeNameCons)
					 .setSource(docc)
					 .execute()
					 .actionGet();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return indexResponse;
	}
	
	*/
/**
	 * 为处理通过车辆查询分组的批量查询
	 * @param SearchResponse 分组查询后的response
	 * @param field 分组的字段
	 * @param field 分组的字段
	 * @return  SearchResponse 查询结果
	 *//*

	public Map <String,ArrayList> multiQueryForGroup(QueryBuilder queryBuilder,FilterBuilder filterBuiler,String field,int size,String sort){
		//获取client
		Client client =conESUtil.getClient();
		MultiSearchResponse multiSearchResponse=null;
		MultiSearchRequestBuilder multirequest = client.prepareMultiSearch();
		Map <String,ArrayList> map =new HashMap<String, ArrayList>();
		
		try {
			SearchResponse response = client.prepareSearch(indexNameCons).setTypes(typeNameCons)
					.setQuery(queryBuilder)
					//.setPostFilter(filterBuiler)
					.addAggregation(AggregationBuilders.terms("terms").field(field).size(2000))
					.execute().actionGet();
			//处理返回结果
			Terms terms = response.getAggregations().get("terms");
			//以下为返回结果的具体处理方法
	        for(Bucket b:terms.getBuckets()){
	        	//System.out.println(b.getKey()+":"+b.getDocCount());
	        	//向Map添加key
	        	map.put(b.getKey(),null);
	        	
	        	SearchRequestBuilder srb = client.prepareSearch()
	            	.setQuery(QueryBuilders.termQuery(field, b.getKey()))
	            	.setSize(size);
	            	//.addSort(sort,SortOrder.ASC);
	        	multirequest.add(srb);
	        }
	        if(!terms.getBuckets().isEmpty()){
	        	MultiSearchResponse sr = multirequest.execute().actionGet();
		        for (MultiSearchResponse.Item item : sr.getResponses()) {
		            SearchResponse responseSingle = item.getResponse();
		            Long count = responseSingle.getHits().getTotalHits();
		            ArrayList result = new ArrayList();
		            result.add(count);
//            	    JSONObject jsonObject = null;
		            for(SearchHit  searchHit: responseSingle.getHits().getHits()){
		            	 String json = searchHit.getSourceAsString();
//		            	 jsonObject = JSONObject.fromObject(json);
		            	 result.add(json);
		            }
//		            if(jsonObject!=null){
//		            	map.put(field,result);
//		            }
		            map.put(field,result);
		        }
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return map;
	}
	*/
/**
	 * 为处理通过车辆查询分组的批量查询
	 * @param SearchResponse 分组查询后的response
	 * @param field 分组的字段
	 * @param field 分组的字段
	 * @return  SearchResponse 查询结果
	 *//*

	public MultiSearchResponse multiQuery(List<QueryBuilder> queryBuilder,List<FilterBuilder> filterBuilder){
		//获取client
		Client client =conESUtil.getClient();
		
		try {
			MultiSearchRequestBuilder multirequest = client.prepareMultiSearch();
			int flag = 0;
			//遍历所有queryBuilder 添加到批量查询中
			if(queryBuilder!=null&&queryBuilder.size()>0){
				for(QueryBuilder q:queryBuilder){
					SearchRequestBuilder query = client.prepareSearch(indexNameCons)
							.setTypes(typeNameCons)
					        .setQuery(q);
					multirequest.add(query);
				}
				flag++;
			}
			//遍历所有filterBuilder 添加到批量查询中
			if(filterBuilder!=null&&filterBuilder.size()>0){
				for(FilterBuilder f:filterBuilder){
					SearchRequestBuilder filter = client.prepareSearch(indexNameCons)
							.setTypes(typeNameCons)
					        .setPostFilter(f);
					multirequest.add(filter);
				}
				flag++;
			}
			
			// 如果批量查询不为空，则执行批量查询 
			if(flag>0){
				MultiSearchResponse sr = multirequest.execute().actionGet();
				return sr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		return null;
	}
	
	*/
/**
	 * 分组查询
	 * @param index 索引
	 * @param type  类型
	 * @param field 分组的字段
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse aggregationQuery(String index,String type,QueryBuilder queryBuilder,String field){
		//获取client
		Client client =conESUtil.getClient();
		SearchResponse response=null;
		
		//执行查询
		try {
			response = client.prepareSearch(indexNameCons).setTypes(typeNameCons)
			.setQuery(queryBuilder)
			.addAggregation(AggregationBuilders.terms("terms").field(field))
			.execute().actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	*/
/**
	 * 分组查询并统计数量
	 * @param  index 索引
	 * @param  type  类型
	 * @param  field  分组字段
	 * @return Map<String,Long>  key为统计的字段，value为文档的个数
	 * @exception/throws [异常类型] [异常说明]
	 *//*

	public Map<String,Long> aggregationCount(String index,String type,QueryBuilder queryBuilder,String field){
		Map<String,Long> resultMap=new HashMap<String,Long>();
		SearchResponse response=null;
		
		try {
			//调用aggregationQuery进行分组查询
			response=aggregationQuery(indexNameCons,typeNameCons,queryBuilder,field);
			
			//处理返回结果
			Terms terms = response.getAggregations().get("terms");
			for(Bucket bucket:terms.getBuckets()){
				resultMap.put(bucket.getKey(),bucket.getDocCount());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resultMap;
	}
	
	*/
/**
	 * 分组查询且对指定字段值求和
	 * @param   index 索引
	 * @param   type  类型
	 * @param   addField  分组字段
	 * @param   sumField  求和字段
	 * @return  Terms    处理结果（具体处理方式可见本方法注释部分）
	 * @exception/throws [异常类型] [异常说明]
	 *//*

	public Terms aggregationSum(String index,String type,String addField,String sumField){
		//获取client
		Client client =conESUtil.getClient();
		
		Terms terms=null;
		try {
			//进行分组查询
			SearchResponse response = client.prepareSearch(indexNameCons).setTypes(typeNameCons)
			.addAggregation(AggregationBuilders.terms("terms")
	        .field(addField).subAggregation(AggregationBuilders.sum("sum").field(sumField)))
			.execute().actionGet();
			
			//处理返回结果
			terms = response.getAggregations().get("terms");
			//以下为返回结果的具体处理方法
//	        for(Bucket b:terms.getBuckets()){
//	        	Sum sum = b.getAggregations().get("sum");
//	        	System.out.println("filedname:"+b.getKey()+"     docCount:"+b.getDocCount()+"  sum"+sum.getValue());
//	        }
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}

		return terms;

	}
	
	public SearchResponse aggregationQuery(QueryBuilder queryBuilder,AggregationBuilder aggBuilder,float minscore){
		//获取client
		Client client =conESUtil.getClient();
		SearchResponse response = null;
		try {
			if(minscore>0f){
				response = client.prepareSearch(indexNameCons)
						.setTypes(typeNameCons) 
						.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
						.setQuery(queryBuilder)
						.addSort("plateNumNond",SortOrder.DESC)
					    .addAggregation(aggBuilder)
					    .setMinScore(minscore)
						.execute()
						.actionGet();
			}else{
				response = client.prepareSearch(indexNameCons)
						.setTypes(typeNameCons) 
						.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
						.setQuery(queryBuilder)
						.addSort("plateNumNond",SortOrder.DESC)
					    .addAggregation(aggBuilder)
						.execute()
						.actionGet();
			}
			
			return response;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally{
			conESUtil.freeClient(client);
		}
		
		
	}
	
	*/
/**
	 * 执行ES简单的查询Match
	 * 刘晓文
	 * 
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse matchQueryData (String[]index,String[] type,QueryBuilder queryBuilder,int startNum,int size){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			response = client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			
			*/
/**
			 * 设置查询条件includeParams包含字段数组，可以多个
			 *//*

			//.setFetchSource(includeParams,excludeParams)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			.setFrom(startNum).setSize(size)
			.execute()
			.actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	*/
/**
	 * 获取最小值
	 * 
	 * @author 刘萌彦
	 * @version 2015-08-06
	 * @param field 计算最小值的字段
	 * @return Double 
	 *//*

	public Double queryMin(String field){
		//获取client
		Client client =conESUtil.getClient();
		InternalMin agg1 = null;
		try {
			SearchResponse sr = client.prepareSearch(indexNameCons)
					.setTypes(typeNameCons)
				    .setQuery(QueryBuilders.matchAllQuery())
				    .addAggregation(
				    		AggregationBuilders.min("agg1").field(field)
				    )
				    .execute().actionGet();
			agg1 = sr.getAggregations().get("agg1");
			return agg1.getValue();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		return null;
	}
	
	*/
/**
	 * 获取大值
	 * 
	 * @author 刘萌彦
	 * @version 2015-08-17
	 * @param field 计算最大值的字段
	 * @return Double 
	 *//*

	public Double queryMax(String field){
		//获取client
		Client client =conESUtil.getClient();
		InternalMax agg1 = null;
		try {
			SearchResponse sr = client.prepareSearch(indexNameCons)
					.setTypes(typeNameCons)
				    .setQuery(QueryBuilders.matchAllQuery())
				    .addAggregation(
				    		AggregationBuilders.max("agg1").field(field)
				    )
				    .execute().actionGet();
			agg1 = sr.getAggregations().get("agg1");
			return agg1.getValue();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		return null;
	}
	
	*/
/**
	 * 卡口统计 批量查询
	 * 
	 * @author 刘萌彦
	 * @version 2015-08-06
	 * @param times 需要统计的时间段
	 * @param number 时间段的个数
	 * @return list<PassDataESVO>
	 *//*

	public void sumData(List<Date []> times,int number,List<String> kako){
		//获取client
		Client client =conESUtil.getClient();
		try {
			MultiSearchRequestBuilder multirequest = client.prepareMultiSearch();
     
			for(Date [] time:times){
				BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
				
				//时间
				QueryBuilder snapTimeBuider = QueryBuilders.rangeQuery("snapTime")
				.from(time[0]).to(time[1]);
				queryBuilder.must(snapTimeBuider);
				
				//卡口
				if(kako!=null && kako.size()>0){
					BoolQueryBuilder kakoBuilder = QueryBuilders.boolQuery();
					for (String kk:kako) {
						QueryBuilder kakoTerm=QueryBuilders.termQuery("passKako",kk);
						kakoBuilder.should(kakoTerm);
					}
					queryBuilder.must(kakoBuilder);
				}
				
				SearchRequestBuilder srb = client.prepareSearch("ts_qdgakk").setTypes("t_pass_data")
				.setQuery(queryBuilder)
				.addAggregation(AggregationBuilders.terms("terms").field("passKako"));
				
				multirequest.add(srb);
			        
			}
			if(times!=null&&times.size()>0){
				MultiSearchResponse sr = multirequest.execute().actionGet();
			    long nbHits = 0;
			    for (MultiSearchResponse.Item item : sr.getResponses()) {
			        SearchResponse response = item.getResponse();
			        nbHits += response.getHits().getTotalHits();
			    }
			    //可以不能除以7 因为到第三个时间周期的开始时间就已经早于卡口第一接受数据的时间
			    System.out.println(nbHits/number);
			}
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
	}
	
	*/
/**
	 * 执行ES简单的查询Match
	 * 刘晓文
	 * 
	 * @param index 索引
	 * @param type  类型
	 * @param qb    查询语句QueryBuilder
	 * @return  SearchResponse 查询结果
	 *//*

	public SearchResponse matchQueryDataALL (String[] index,String[] type,QueryBuilder queryBuilder){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询，返回结果Json
		SearchResponse response=null;
		try {
			response = client.prepareSearch(indexNameCons)
			.setTypes(typeNameCons)
			
			*/
/**
			 * 设置查询条件includeParams包含字段数组，可以多个
			 *//*

			//.setFetchSource(includeParams,excludeParams)
			.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setQuery(queryBuilder)
			//.setFrom(startNum).setSize(size)
			.execute()
			.actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		}finally{
			//使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		
		return response;
	}
	
	public MultiSearchResponse multiRequest(List<SearchRequestBuilder> list) {
		// 获取client
		Client client = conESUtil.getClient();
		
		MultiSearchRequestBuilder multirequest = client.prepareMultiSearch();
		
		
		MultiSearchResponse  sr = null;
		try {
			for(SearchRequestBuilder request:list){
				if(request!=null){
					multirequest.add(request);
				}
			}
			sr = multirequest.execute().actionGet();
		} catch (ElasticsearchException e) {
			e.printStackTrace();
		} finally {
			// 使用client完毕后必须释放。
			conESUtil.freeClient(client);
		}
		return sr;
	}
//	*/
/**
//	 * es修改
//	 * 
//	 * @param index
//	 * @param type
//	 * @param field
//	 * @param value
//	 * @throws IOException
//	 * @throws JSONException
//	 *//*

//	public UpdateResponse update(String index,String type,String id,String field,String value) throws IOException, JSONException{
//				//获取需要更改的记录
//				//获取client
//				Client client =conESUtil.getClient();
//				UpdateRequest updateRequest = new UpdateRequest(indexNameCons, typeNameCons, id)
//				.doc(jsonBuilder()
//			    .startObject()
//			    .field(field, value)
//			    .endObject());
//				UpdateResponse updateResponse = null;
//				//System.out.println("执行更新的索引名称为："+indexNameCons);
//				try {
//					updateResponse = client.update(updateRequest).get();
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				} catch (ExecutionException e) {
//					e.printStackTrace();
//				}finally{
//					//使用client完毕后必须释放。
//					conESUtil.freeClient(client);
//				}
//				return updateResponse;
//			}

	*/
/**
	 * ES查询结果封装为PassDataESVO
	 * 
	 * @author 刘萌彦
	 * @version 2015-08-06
	 * @param searchResponse  ES查询结果
	 * @return list<PassDataESVO>
	 *//*

//	public static List<PassDataESVO> jsonToBean(SearchResponse searchResponse){
//		List<PassDataESVO> list=new ArrayList<PassDataESVO>();
//		try{
//			if(searchResponse!=null){
//				for(SearchHit  searchHit: searchResponse.getHits().getHits()){
//					PassDataESVO esVO = new PassDataESVO();
//					String str = searchHit.getSourceAsString();
//					str=str.substring(0,str.length()-1)+",\"id\":\""+searchHit.getId()+"\"}";
//					
//					esVO = (PassDataESVO) JsonUtil.pass2Bean(str, PassDataESVO.class);
//					if(esVO.getPlateType().equals("41")||StringUtils.isBlank(esVO.getPlateNum())
//							||esVO.getPlateNum().length()<7){
//						esVO.setPlateNum("未识别");
//					}
//					
//					esVO.setSnapTimeText(DateUtil.getDateToStr(esVO.getSnapTime(), "yyyy/MM/dd HH:mm:ss"));
//					list.add(esVO);
//				}
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		return list;
//	}
	*/
/**
	 * ES查询结果封装为PassDataESVO
	 * 
	 * @author 王彦坤
	 * @version 2014-12-18
	 * @param searchResponse  ES查询结果
	 * @return list<PassDataESVO>
	 *//*

//	public static  List<PassDataESVO> responseToBean(SearchResponse searchResponse){
////		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		List<PassDataESVO> list=new ArrayList<PassDataESVO>();
//		try{
//			if(searchResponse!=null){
//				for(SearchHit  searchHit: searchResponse.getHits().getHits()){
//					PassDataESVO esVO = new PassDataESVO();
//					
//					Map<String, Object> obj=searchHit.getSource();
//					*/
/**拼接可以直接转化的字符串*//*

//					String str="{";
//					// Set类型的key值集合，并转换为迭代器
//					Iterator it = obj.keySet().iterator();
//					while(it.hasNext()){
//						// 获取 key值
//						String key = (String) it.next();
//						//获取 value值
//						Object objVal = obj.get(key);
//						if(objVal==null||"".equals(objVal.toString())||"null".equals(objVal.toString())){
//							continue;
//						}
//						String objValStr=objVal.toString();
//						//为json中的key添加双引号，删除大数据查询结果中内容为"null"的字段
//						str += "\""+key+"\":\""+(objVal==null?"":objValStr)+"\",";
//					}
//					str=str.substring(0,str.length()-1);
//					str+="}";
//					esVO = (PassDataESVO) JsonUtil.pass2Bean(str, PassDataESVO.class);
//					list.add(esVO);
//				}
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		return list;
//	}
	
	*/
/**
	 * ES搜索
	 * @project ES
	 * @method searchByBuilder
	 * @param indexs
	 * @param types
	 * @param queryBuilder
	 * @param filterBuilder
	 * @param fromNum
	 * @param size
	 * @return  SearchResponse
	 * @author BY: LC 2015-10-29 下午05:07:32
	 *//*

	public  SearchResponse searchByBuilder(String[] indexs,String[] types,QueryBuilder queryBuilder,FilterBuilder filterBuilder,Integer fromNum,Integer size,String [] highlightFields,String highlightTag)
	{
		    Client client =conESUtil.getClient();
		    SearchResponse response = null;
		    //创建查询索引,参数表示要查询的索引库
			SearchRequestBuilder searchRequestBuilder;
			try {
				searchRequestBuilder = null;
				
				//设置索引
				if(indexs!=null)
				{
					searchRequestBuilder=client.prepareSearch(indexs);
				}
				else
				{
					searchRequestBuilder=client.prepareSearch();
				}
				
				//设置索引类型
				if(types!=null)
				{
					searchRequestBuilder.setTypes(types);
				}
				
				//设置查询类型 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询 2.SearchType.SCAN =扫描查询,无序 3.SearchType.QUERY_AND_FETCH:最原始（也可能是最快的）
				searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
				
				//设置查询QueryBuilder
				searchRequestBuilder.setQuery(queryBuilder);
				
				if(filterBuilder!=null)
				{
				    //查询过滤器过滤
					searchRequestBuilder.setPostFilter(filterBuilder);
				}
				
				//分页应用
				//设置起始位置
				if(fromNum!=null)
				{
					searchRequestBuilder.setFrom(fromNum);
				}
				//设置返回的记录数目
				if(size!=null)
				{
					searchRequestBuilder.setSize(size);
				}
				
				//设置是否按查询匹配度排序
				searchRequestBuilder.setExplain(true);
				

				//设置高亮显示的字段
				if(highlightFields!=null)
				{
					for(String h:highlightFields)
					{
						searchRequestBuilder.addHighlightedField(h);
					}
					//加高亮标签
				    searchRequestBuilder.setHighlighterPreTags("<"+highlightTag+">");
				    searchRequestBuilder.setHighlighterPostTags("</"+highlightTag+">");
					//执行搜索
				    response =searchRequestBuilder.execute().actionGet();  
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				//使用client完毕后必须释放。
				conESUtil.freeClient(client);
			}
	
		
		          
           return response;
	}
	
	*/
/**
	 * 搜索视频分析数据
	 * @param text
	 * @param fromNum
	 * @param size
	 * @param highlightTag
	 * @param beginDate
	 * @param endDate
	 * @return
	 *//*

	public  Map<String,Object> searchLXFXByString(String text,Integer fromNum,Integer size,String highlightTag,String beginDate,String endDate)
	{
		String indexs[]=new String[]{"gqsp"};
		 String types[]=new String[]{"gqsp_ssfx","gqsp_kxfx"};
		 //设置高亮显示的字段
		 String [] highlightFields=new String[]{"tagName","tag","cameraId","cameraName","date","url","url_1"};
		 
		 
		 RangeFilterBuilder rangeFilterBuilder= null;
		 
		 if(beginDate!=null && !"".equals(beginDate))
		 {
			 rangeFilterBuilder=FilterBuilders.rangeFilter("date").gte(beginDate);
		 }
		 if(endDate!=null && !"".equals(endDate))
		 {
			 if(rangeFilterBuilder!=null)
			 {
				 rangeFilterBuilder.lte(endDate);
			 }
			 else
			 {
				 rangeFilterBuilder=FilterBuilders.rangeFilter("date").lte(endDate);
			 }
		 }
		 		 
		 SearchResponse response=searchByBuilder(indexs,types,QueryBuilders.queryString(text),rangeFilterBuilder,fromNum,size,highlightFields,highlightTag);
		 return searchResponse2Map(response);
	}
	
	
	*/
/**
	 * searchResponse对象转换成Map
	 * @project ES
	 * @method searchResponse2Map
	 * @param response
	 * @return  Map<String,Object>
	 * @author BY: LC 2015-11-3 下午02:24:00
	 *//*

	public Map<String,Object> searchResponse2Map(SearchResponse response)
	{
		Map<String,Object>  map =new HashMap<String,Object>();
        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();
        map.put("TotalHits", searchHits.getTotalHits());
        map.put("TookInMillis", response.getTookInMillis());
        //没有查询到数据时，searchHits.getMaxScore()返回 “NaN”，所以此处处理一下
        if(searchHits.getTotalHits()!=0)
        {
        	map.put("MaxScore", searchHits.getMaxScore());
        }
        else
        {
        	map.put("MaxScore", 0);
        }
        //System.out.println("查询总数："+searchHits.getTotalHits());
        //System.out.println("耗时："+response.getTookInMillis());
        
        List<Map<String,Map<String,Object>>> list=new ArrayList<Map<String,Map<String,Object>>>();
        for (int i = 0; i < hits.length; i++) 
        {
            SearchHit hit = hits[i];
            Map<String, Object> result = hit.getSource();
            //System.out.println("索引："+hit.getIndex());
            //System.out.println("类型："+hit.getType());
            //System.out.println(i+"====>得分："+hit.getScore()+"，索引："+hit.getIndex()+",类型："+hit.getType()+",源："+result);
            
            
            //获取对应的高亮域
            Map<String, HighlightField> high = hit.highlightFields(); 
            Map<String,Object> tHigh=new HashMap<String, Object>();
            //System.out.println("----------------->高亮："+high);
            //遍历高亮区域
            for (Map.Entry<String,HighlightField> entry : high.entrySet()) {  
            	  
                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
               
                Text[] titleTexts = entry.getValue().getFragments();   
                String hString = "";  
                for(Text text : titleTexts){    
                	hString += text;  
                }
            
                tHigh.put(entry.getKey(), hString);
              
            } 
         
            Map<String,Map<String,Object>> ret=new HashMap<String,Map<String,Object>>();
            ret.put("_source", result);
            ret.put("highlight",tHigh);
            
            //设置索引及类型，得分
            Map<String,Object> tIndex=new HashMap<String, Object>();
            tIndex.put("index",hit.getIndex());
            tIndex.put("type",hit.getType());
            tIndex.put("score", hit.getScore());
            ret.put("index", tIndex);         
            
            //添加到list中
            list.add(ret);
            
        }
        
        map.put("hits", list);
        
        System.out.println("全文检索 ---------->search success ..");		
	    return map;

	}

	*/
/**
	 * 在指定索引和指定索引类型检索信息
	 * @param text
	 * @param fromNum
	 * @param size
	 * @param highlightTag
	 * @param beginDate
	 * @param endDate
	 * @return
	 *//*

	public  Map<String,Object> searchFromIndexByString(String [] indexs,String [] indexTypes,String text,Integer fromNum,Integer size,String highlightTag,String beginDate,String endDate)
	{
		 //设置高亮显示的字段
		 String [] highlightFields=new String[]{"tagName","tag","cameraId","cameraName","date","url","url_1"};
		 		 
		 RangeFilterBuilder rangeFilterBuilder= null;
		 
		 if(beginDate!=null && !"".equals(beginDate))
		 {
			 rangeFilterBuilder=FilterBuilders.rangeFilter("date").gte(beginDate);
		 }
		 if(endDate!=null && !"".equals(endDate))
		 {
			 if(rangeFilterBuilder!=null)
			 {
				 rangeFilterBuilder.lte(endDate);
			 }
			 else
			 {
				 rangeFilterBuilder=FilterBuilders.rangeFilter("date").lte(endDate);
			 }
		 }
		 		 
		 SearchResponse response=searchByBuilder(indexs,indexTypes,QueryBuilders.queryString(text),rangeFilterBuilder,fromNum,size,highlightFields,highlightTag);
		 return searchResponse2Map(response);
	}
	*/
/**
	 * 查询总数count
	 * 
	 * @param index
	 * @param type
	 * @param queryBuilder
	 * @return
	 *//*

	public Long queryEsCount(QueryBuilder queryBuilder){
		//获取client
		Client client =conESUtil.getClient();
		//执行ES查询
		CountResponse resCount = null;
		try{
			resCount = client.prepareCount(indexNameCons)
					.setTypes(typeNameCons)
					.setQuery(queryBuilder)
					.execute()
					.actionGet();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//释放client
			conESUtil.freeClient(client);
		}
		return resCount.getCount();
	}
	
	*/
/**
	 * 将Response 转化为Map
	 *//*

	public Map<String, Object> convertResponse(Map<String, Object> map, SearchResponse searchResponse) {
		List<PassBean> list = new ArrayList<PassBean>();
		if(searchResponse==null || searchResponse.getHits()==null){
			map.put("count",0);
			map.put("time", 0.0141);
			map.put("list",list);
			return map;
		}
		long count = searchResponse.getHits().getTotalHits();
		Long time = searchResponse.getTookInMillis();
		
		map.put("count",count);	
		map.put("time", (double)time/1000);
	   
		for(SearchHit  searchHit: searchResponse.getHits().getHits()){
			PassBean bean = new PassBean();			
			String str = searchHit.getSourceAsString();
			System.out.println("....查询出来的Json:<br>"+str);
			
			
			
			//bean = (PassBean) JSONObject.parseObject(str,PassBean.class);
			bean = (PassBean) JsonUtil.readValue(str,PassBean.class);
			*/
/**
			 * 将非正常车牌统一设置  
			 * null,"0","无牌车","未识别","-"
			 *//*

			String  n = bean.getPlateNumNond() ;
			*/
/*if(n == null || "0".equals(n.trim()) || "无牌车".equals(n.trim())||"未识别".equals(n.trim())||"-".equals(n.trim())){
				bean.setPlateNumNond("0");
				bean.setPlateType("41");
				//bean.setPlateTypeName(""); 
			}*//*

			if(bean.getPlateType().equals("41") || StringUtils.isBlank(bean.getPlateNumNond()) || bean.getPlateNumNond().length()<7){
					bean.setPlateNumNond("未识别");
			}			
			//bean.setSnapTimeText(DateUtil.getDateToStr(esVO.getSnapTime(), "yyyy/MM/dd HH:mm:ss"));
			
			list.add(bean);
		}
		
		map.put("list",list);
		return map;
	}
}*/
